<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      div {
        float: left;
        width: 150px;
        padding-left: 80px;
        height: 130px;
        padding-top: 80px;
        background-color: cornflowerblue;
        margin: 10px;
        font-size: 20px;
      }
    </style>
  </head>
  <body>
    <div>1</div>
    <div>2</div>
    <div>3</div>
    <div>4</div>
    <div>5</div>
    <div>6</div>
    <div>7</div>
    <div>8</div>
    <div>9</div>
    <div>10</div>
    <script>
      //非闭包
      // let divs = document.querySelectorAll('div')
      // for (let i = 0; i < divs.length; i++) {
      //   divs[i].addEventListener('click', function () {
      //     alert(i)
      //   })
      // }

      //闭包
      let divs = document.querySelectorAll('div')
      for (var i = 0; i < divs.length; i++) {
        ;(function (index) {
          divs[index].addEventListener('click', function () {
            alert(index)
          })
        })(i)
      }

      // var i
      // let allLi = document.querySelectorAll('div')

      // for (i = 0; i < allLi.length; i++) {
      //   ;(function (i) {
      //     allLi[i].addEventListener('click', function () {
      //       console.log(i)
      //       alert(allLi[i].innerHTML)
      //     })
      //   })(i)
      // }
    </script>
  </body>
</html>
